package com.py.credit.service.impl;

import com.py.credit.common.Page;
import com.py.credit.common.ServiceException;
import com.py.credit.dao.WarningDealDao;
import com.py.credit.entity.WarningDealEntity;
import com.py.credit.service.WarningDealService;
import com.py.credit.utils.DingZhiConstant;
import com.py.credit.utils.SQLBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class WarningDealServiceImpl implements WarningDealService {

    @Autowired
    private WarningDealDao warningDealDao;

    @Override
    public List<Map<String, Object>> selectWarningDealListByConditionForPage(List<String> showColumns, String[] additionalColumns, String condition, Page page) {
        if (CollectionUtils.isEmpty(showColumns)) {
            throw new ServiceException("至少选择一列");
        }

        List<String> conditions = SQLBuilder.createConditionSql(condition);

        return warningDealDao.selectWarningDealListByConditionForPage(showColumns, additionalColumns, conditions, page);
    }

    @Override
    public LinkedHashMap selectDetailById(String id) {
        LinkedHashMap map = new LinkedHashMap();
        LinkedHashMap detail = warningDealDao.selectDetailById(id);
        map.put("detail", detail);

        String[] ajbhList = ((String) detail.get("ajbh")).split(",");
        map.put("list", warningDealDao.selectAjbhList(Arrays.asList(ajbhList)));
        return map;
    }

    @Override
    public int selectWarningDealDeptNum(Long deptId, String flag, String startTime, String endTime) {
        return warningDealDao.selectWarningDealDeptNum(deptId, flag, startTime, endTime);
    }

    @Override
    public List<LinkedHashMap> selectWarningDealChartTop10(String order, String startTime, String endTime) {
        return warningDealDao.selectWarningDealChartTop10(order, startTime, endTime);
    }

    @Override
    public int addLog(WarningDealEntity warningDealEntity) {
        warningDealDao.addLog(warningDealEntity);
        return warningDealEntity.getId();
    }

    @Override
    public void updateLog(int logId, String ajbh) {
        warningDealDao.updateLog(logId, ajbh);
    }

    @Override
    public void excelExport(HttpServletResponse response, String deptId, String startTime, String endTime) throws IOException {
        if (StringUtils.isBlank(deptId)) {
            queryTableExecle(response, startTime, endTime);
        } else {
            queryUserTableExecle(response, deptId, warningDealDao.selectDeptNameById(Long.parseLong(deptId)), startTime, endTime);
        }
    }

    private void queryTableExecle(HttpServletResponse response, String startTime, String endTime) throws IOException {
        // 生成提示信息
        response.setContentType("application/vnd.ms-excel");
        HSSFWorkbook workbook = null;
        OutputStream fOut = null;
        String codedFileName = "各部门预警处理监控分析";

        codedFileName = URLEncoder.encode(codedFileName, "UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
        // 产生工作簿对象
        workbook = new HSSFWorkbook();
        // 产生工作表对象

        String[] strBT1 = {"部门名称", "反馈率"};
        String[] strBT2 = {"部门名称", "反馈率"};

        List<LinkedHashMap> chartDesc = warningDealDao.selectWarningDealChartTop10(DingZhiConstant.ORDER_BY_DESC, startTime, endTime);
        List<LinkedHashMap> chartAsc = warningDealDao.selectWarningDealChartTop10(DingZhiConstant.ORDER_BY_ASC, startTime, endTime);

        HSSFSheet sheet = workbook.createSheet();
        String sheet1Name = "各部门预警事件反馈率前10位排名";
        workbook.setSheetName(0, sheet1Name);
        HSSFRow row = null;
        HSSFCell cell = null;
        // 创建标题行
        row = sheet.createRow(0);
        for (int i = 0; i < strBT1.length; i++) {
            cell = row.createCell(i);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(strBT1[i]);
        }
        for (int i = 0; i < chartDesc.size(); i++) {
            row = sheet.createRow((int) i + 1);
            cell = row.createCell(0);//创建一列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(chartDesc.get(i).get("deptName").toString());
            cell = row.createCell(1);//创建一列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(chartDesc.get(i).get("rate").toString());
        }

        HSSFSheet sheet2 = workbook.createSheet();
        String sheet2Name = "各部门预警事件反馈率后10位排名";
        workbook.setSheetName(1, sheet2Name);
        row = null;
        cell = null;
        // 创建标题行
        row = sheet2.createRow(0);
        for (int i = 0; i < strBT2.length; i++) {
            cell = row.createCell(i);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(strBT2[i]);
        }
        for (int i = 0; i < chartAsc.size(); i++) {
            row = sheet2.createRow((int) i + 1);
            cell = row.createCell(0);//创建一列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(chartAsc.get(i).get("deptName").toString());
            cell = row.createCell(1);//创建一列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(chartAsc.get(i).get("rate").toString());
        }

        fOut = response.getOutputStream();
        workbook.write(fOut);
        workbook.close();
        fOut.flush();
        fOut.close();
    }

    private void queryUserTableExecle(HttpServletResponse response, String deptId, String deptName, String startTime, String endTime) throws IOException {
        // 生成提示信息
        response.setContentType("application/vnd.ms-excel");
        HSSFWorkbook workbook = null;
        OutputStream fOut = null;
        String codedFileName = deptName + "各用户预警处理监控分析";
        codedFileName = URLEncoder.encode(codedFileName, "UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
        // 产生工作簿对象
        workbook = new HSSFWorkbook();
        // 产生工作表对象

        String[] strBT1 = {"预警提示事件", "处理反馈事件", "预警事件处理率"};


        HSSFSheet sheet = workbook.createSheet();
        String sheet1Name = "部门用户预警处理监控统计";
        workbook.setSheetName(0, sheet1Name);
        HSSFRow row = null;
        HSSFCell cell = null;
        // 创建标题行
        row = sheet.createRow(0);
        for (int i = 0; i < strBT1.length; i++) {
            cell = row.createCell(i);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(strBT1[i]);
        }

        int feedbackNum = warningDealDao.selectWarningDealDeptNum(Long.parseLong(deptId), DingZhiConstant.IS_FEEDBACK, startTime, endTime);
        int totalNum = warningDealDao.selectWarningDealDeptNum(Long.parseLong(deptId), null, startTime, endTime);
        String pieNum = "0";

        if (0 != totalNum && 0 != feedbackNum) {
            DecimalFormat format = new DecimalFormat("#.00");
            pieNum = format.format(feedbackNum * 1D / totalNum * 100);
        }

        row = sheet.createRow(1);
        cell = row.createCell(0);//创建一列
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(totalNum);
        cell = row.createCell(1);//创建一列
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(feedbackNum);
        cell = row.createCell(2);//创建一列
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(pieNum);

        fOut = response.getOutputStream();
        workbook.write(fOut);
        workbook.close();
        fOut.flush();
        fOut.close();
    }
}
